package com.jamaskii.ecdict;

import com.jamaskii.utils.IOUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class PronunciationStream {
    private String path;

    public PronunciationStream(String pronunciationPath){
        this.path=pronunciationPath;
    }

    public String getPronunciation(String word, int type){
        String filName="";
        if(type==0){
            filName=path+"/US/"+word+".m4a";
        }else if(type==1){
            filName=path+"/GB/"+word+".m4a";
        }
        File objFile=new File(filName);
        if(objFile.exists()){
            return objFile.getAbsolutePath();
        }else{
            return null;
        }
    }

    public static String getPronunciation(String word, int type, String pronPath){
        String filName="";
        if(type==0){
            filName=pronPath+"/US/"+word+".m4a";
        }else if(type==1){
            filName=pronPath+"/GB/"+word+".m4a";
        }
        File objFile=new File(filName);
        if(objFile.exists()){
            return objFile.getAbsolutePath();
        }else{
            return null;
        }
    }

    public static boolean downloadPronunciation(String word, int type, String saveDir){
        byte[] data;
        try{
            URL url = new URL("http://dict.youdao.com/dictvoice?type="+type+"&audio="+word.replace(" ", "%20"));
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            data= IOUtils.readBytes(connection.getInputStream());
            String fileName="";
            if(type==0){
                fileName=saveDir+"/US/"+word+".m4a";
            }
            else if(type==1){
                fileName=saveDir+"/GB/"+word+".m4a";
            }
            return IOUtils.fileWriteBytes(fileName,data);
        }catch (MalformedURLException e){
            return false;
        }catch (IOException e){
            return false;
        }
    }

    public boolean downloadPronunciation(String word, int type){
        byte[] data;
        try{
            URL url = new URL("http://dict.youdao.com/dictvoice?type="+type+"&audio="+word.replace(" ", "%20"));
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            data= IOUtils.readBytes(connection.getInputStream());
            String fileName="";
            if(type==0){
                fileName=path+"/US/"+word+".m4a";
            }
            else if(type==1){
                fileName=path+"/GB/"+word+".m4a";
            }
            return IOUtils.fileWriteBytes(fileName,data);
        }catch (MalformedURLException e){
            return false;
        }catch (IOException e){
            return false;
        }
    }

}
